const app = getApp()
const http = require('../../api/index.js')
const request = require('../../utils/request')

Page({
  data: {
    baseUrl: request.baseURL,
    openId:"",
    imageUrl: "",
    username: "",
  },
  // 修改完成按钮
  onclickGoBack() {
    wx.navigateBack()
    this.updateInfo(this.data)
  },
  //头像更改
  onChooseAvatar(e) {
    const avatarUrl = e.detail.avatarUrl
    var self = this;
    let token = wx.getStorageSync('userInfo').token?wx.getStorageSync('userInfo').token:null
    wx.uploadFile({
      filePath: avatarUrl,
      name: 'file',
      url: request.baseURL + '/common/upload',
      header:{
        'content-type':'qpplication/json',
        'Authorization':`Bearer ${token}`,
      },
      success:(res)=>{
        const uploadData = JSON.parse(res.data);
        self.setData({
          imageUrl: uploadData.fileName
        })
      }
    })
  },
  onLoad() {
  },
  onShow(){
    this.onUserinfoInit();
  },
  // 加载缓存中的个人信息
  onUserinfoInit() {
    const userInfo=wx.getStorageSync('userInfo')
    this.setData({
      imageUrl: userInfo.imageUrl,
      username: userInfo.username,
      openId:userInfo.openId
    })
  },
  // 调用修改接口
  updateInfo(data){
    http.updateUserInfo(data).then(res=>{
      if(res.code == 200){
        var userInfo=wx.getStorageSync('userInfo')
        userInfo.imageUrl = this.data.imageUrl
        userInfo.username = this.data.username
        wx.setStorageSync('userInfo', userInfo)
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 500
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 500
        })
        return false
      }
    })
  }
})